﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DONGACS.DTO;
using QLPKWeb.BussinessDelegate.PhanQuyen;
using QLPKWeb.Controllers.Base;
using QLPKWeb.Models.FormBean.PhanQuyen;
using Webdiyer.WebControls.Mvc;
using DONGACS.Common;

namespace QLPKWeb.Controllers
{
    public class JobTitlesController : BaseController
    {
        JobTitlesServiceDelegate JobTitlesServiceDelegate = new JobTitlesServiceDelegate();
        UsersServiceDelegate UsersServiceDelegate = new UsersServiceDelegate();

        //
        // GET: /JobTitles/

        public ActionResult List(int? id, JobTitlesForm form, string JobTitlesSearch)// id : page number
        {
            //JobTitlesForm form = new JobTitlesForm();
            if (string.IsNullOrEmpty(form.JobTitlesSearch))
                form.JobTitlesSearch = JobTitlesSearch;
            if (string.IsNullOrEmpty(form.JobTitlesSearch))
            {
                BuildJobTitlesList(form);
                form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, id ?? 1, CommonVariables.PaggedItemsPerPage);
            }
            else
            {
                form.JobTitlesDtoList = JobTitlesServiceDelegate.GetAllJobTitlesByName(form.JobTitlesSearch);
                form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, id ?? 1, CommonVariables.PaggedItemsPerPage);
            }
            form.PageNumber = id ?? 1;
            form.ID = -1;
            form.CreateDate = DateTime.Now;
            form.UpdateDate = DateTime.Now;
            
            if(Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }
            
            return View("Index", form);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create(int? id)// id : page number
        {
            return Redirect("~/JobTitles/List/" + id);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Create(JobTitlesForm form, string JobTitlesSearch)
        {
            //Lấy thông tin Job Title mới từ Form
            JobTitlesDto newjobTitles = this.JobTitlesServiceDelegate.BuildNewJobTitles(form);
            
            //Lưu Job Titele mới xuống database
            int idReturn = -1;
            //bool isCreateJobTitle = this.JobTitlesServiceDelegate.AddNewJobTitles(newjobTitles, ref idReturn);
            bool isCreateJobTitle = this.JobTitlesServiceDelegate.AddNewEntity(newjobTitles, ref idReturn);

            //Thông báo kết quả tạo Job Title
            form.MessageCreateJobTitles = isCreateJobTitle ? "Tạo Chức vụ thành công !" : "Tạo Chức vụ thất bại, làm ơn thử lại !";

            //Refesh form
            //BuildJobTitlesList(form);
            form.ID = idReturn;
            form.CreateDate = DateTime.Now;
            form.UpdateDate = DateTime.Now;

            if (Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }

            
            //Phân trang
            //int id = 1;
            //form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);
            if (string.IsNullOrEmpty(form.JobTitlesSearch))
                form.JobTitlesSearch = JobTitlesSearch;
            if (string.IsNullOrEmpty(form.JobTitlesSearch))
            {
                BuildJobTitlesList(form);
                form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);
            }
            else
            {
                form.JobTitlesDtoList = JobTitlesServiceDelegate.GetAllJobTitlesByName(form.JobTitlesSearch);
                form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);
            }

            return View("Index", form);
        }


        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int? id)// id : page number
        {
            return Redirect("~/JobTitles/List/" + id);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(JobTitlesForm form, string JobTitlesSearch)
        {
            form.ID = form.JobTitleID;

            //Lấy thông tin Job Title mới từ Form
            JobTitlesDto newjobTitles = this.JobTitlesServiceDelegate.BuildEditJobTitles(form);

            //Lưu Job Titele mới xuống database
            
            bool isUpdateJobTitle = this.JobTitlesServiceDelegate.Update(newjobTitles);

            //Thông báo kết quả tạo Job Title
            form.MessageEditJobTitles = isUpdateJobTitle ? "Cập nhật Chức vụ thành công !" : "Cập nhật Chức vụ thất bại, làm ơn thử lại !";

            //Refesh form
            //BuildJobTitlesList(form);
            
            form.CreateDate = newjobTitles.CreateDate;
            form.UpdateDate = newjobTitles.UpdateDate;

            if (Convert.ToInt32(Session["USERID"]) != 0)
            {
                var userLogin = UsersServiceDelegate.GetUsersById(Convert.ToString(Session["USERID"]));
                form.CreateByUser = form.UpdateByUser = userLogin.LastName + " " + userLogin.FirstName;
            }
            else
            {
                form.CreateByUser = form.UpdateByUser = string.Empty;
            }

            //Phân trang
            //int id = 1;
            //form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);
            if (string.IsNullOrEmpty(form.JobTitlesSearch))
                form.JobTitlesSearch = JobTitlesSearch;
            if (string.IsNullOrEmpty(form.JobTitlesSearch))
            {
                BuildJobTitlesList(form);
                form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);
            }
            else
            {
                form.JobTitlesDtoList = JobTitlesServiceDelegate.GetAllJobTitlesByName(form.JobTitlesSearch);
                form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);
            }

            return View("Index", form);
        }

        public ActionResult Delete(string jobTiTleID)
        {
            this.JobTitlesServiceDelegate.Delete(jobTiTleID);
            return RedirectToAction("List");
        }

        public JsonResult JobTitlesEditAjax(int id)
        {
            JobTitlesDto dto = this.JobTitlesServiceDelegate.GetJobTitlesById(id.ToString());
            
            var userCreate = UsersServiceDelegate.GetUsersById(Convert.ToString(dto.CreateBy));
            var userUpdate = UsersServiceDelegate.GetUsersById(Convert.ToString(dto.UpdateBy));

            dto.CreateByUser = dto.CreateBy != 0 && userCreate != null ? userCreate.LastName + " " + userCreate.FirstName : string.Empty;
            dto.UpdateByUser = dto.UpdateBy != 0 && userUpdate != null ? userUpdate.LastName + " " + userUpdate.FirstName : string.Empty;
            dto.CreateDateString = dto.CreateDate.ToString("dd/MM/yyyy");
            dto.UpdateDateString = dto.UpdateDate.ToString("dd/MM/yyyy");

            return Json(dto, JsonRequestBehavior.AllowGet);
        }

        public JsonResult JobTitlesNewAjax()
        {
            var userLogin = UsersServiceDelegate.GetUsersById(Session["USERID"].ToString());
            var newObj = new object[2] { userLogin != null ? userLogin.LastName + " " + userLogin.FirstName : string.Empty, DateTime.Now };
            
            return this.Json(newObj, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DoCheckJobTitleIsExistAjax(string jobTitle)
        {
            JobTitlesDto dto = this.JobTitlesServiceDelegate.GetJobTitleByName(jobTitle);

            bool result = dto != null ? true : false;
            
            return this.Json(result, JsonRequestBehavior.AllowGet);
        }

        private void BuildJobTitlesList(JobTitlesForm form)
        {
            //Lấy danh sách user không bị đánh dấu IsDelete = 1
            form.JobTitlesDtoList = JobTitlesServiceDelegate.GetAllEntities();

            foreach (var jobTitlesDto in form.JobTitlesDtoList)
            {   //lấy tên ngừoi tạo hay thay đổi thông tin Roles
                var userUpdate = UsersServiceDelegate.GetUsersById(Convert.ToString(jobTitlesDto.UpdateBy));
                var userCreate = UsersServiceDelegate.GetUsersById(Convert.ToString(jobTitlesDto.CreateBy));

                try
                {
                    jobTitlesDto.UpdateByUser = jobTitlesDto.UpdateBy != 0 ? userUpdate.LastName + " " + userUpdate.FirstName : string.Empty;

                    jobTitlesDto.CreateByUser = jobTitlesDto.CreateBy != 0 ? userCreate.LastName + " " + userCreate.FirstName : string.Empty;
                }
                catch (Exception)
                {

                 //   jobTitlesDto.UpdateByUser = jobTitlesDto.UpdateBy != 0 ? userUpdate.LastName + " " + userUpdate.FirstName : string.Empty;

                 //   jobTitlesDto.CreateByUser = jobTitlesDto.CreateBy != 0 ? userCreate.LastName + " " + userCreate.FirstName : string.Empty;
                }
               
            }
        }

        //Search
        //public ActionResult Search(int? id, string JobTitlesSearch)
        //{
        //    JobTitlesForm form = new JobTitlesForm();
        //    form.JobTitlesDtoList = JobTitlesServiceDelegate.GetAllJobTitlesByName(JobTitlesSearch);
        //    form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, id??1, CommonVariables.PaggedItemsPerPage);
        //    form.PageNumber = id ?? 1;
        //    form.ID = -1;
        //    form.CreateDate = DateTime.Now;
        //    form.UpdateDate = DateTime.Now;
        //    form.CreateByUser = SessionDetail.USERID != 0 ? UsersServiceDelegate.GetUsersById(SessionDetail.USERID.ToString()).UserName : string.Empty;
        //    form.UpdateByUser = SessionDetail.USERID != 0 ? UsersServiceDelegate.GetUsersById(SessionDetail.USERID.ToString()).UserName : string.Empty;

        //    return View("Index", form);
        //}
        //[AcceptVerbs(HttpVerbs.Post)]
        //[ValidateInput(false)]
        //public ActionResult Search(JobTitlesForm form)
        //{
        //    //JobTitlesForm form = new JobTitlesForm();
        //    form.JobTitlesDtoList = JobTitlesServiceDelegate.GetAllJobTitlesByName(form.JobTitlesSearch);
        //    form.JobTitlesPagedList = new PagedList<JobTitlesDto>(form.JobTitlesDtoList, form.PageNumber, CommonVariables.PaggedItemsPerPage);
        //    //form.PageNumber = id ?? 1;
        //    form.ID = -1;
        //    form.CreateDate = DateTime.Now;
        //    form.UpdateDate = DateTime.Now;
        //    form.CreateByUser = SessionDetail.USERID != 0 ? UsersServiceDelegate.GetUsersById(SessionDetail.USERID.ToString()).UserName : string.Empty;
        //    form.UpdateByUser = SessionDetail.USERID != 0 ? UsersServiceDelegate.GetUsersById(SessionDetail.USERID.ToString()).UserName : string.Empty;

        //    return View("Index", form);
        //}
    }
}
